var params = {};
var defaultPageSize = 10;
var currentPage = 1;
var pageSize = defaultPageSize;
$(function(){
	loadGrid();
	
	$('.check').on('click',search);
	$('.empty').on('click',emptySearch);
	
	//新增或更新菜单
	$('.add').on('click',add);
});


function loadGrid(){
	params.currentPage = currentPage;
	params.pageSize = pageSize;
	$.ajax({
		url: webUrl+'sysmenu/pageSysMenu.do',
		type:'post',
		data:params
	}).done(function(data){
		var result = data.bo;
		var pager = {};
		$('#menuGrid').datagrid({
			fitColumns:true,
			singleSelect:true,
			pagination:true,
			remoteSort:false,
			multiSort:true,
			loadMsg:"数据加载中，请稍后……",
			data:result.list,
			columns:[[
			          {field:'_itemNo',title:'序号',align:'center',width:50,formatter:formatId},
			          {field:'name',title:'菜单名称',width:150,sortable:true},
			          {field:'level',title:'菜单类型',width:100,sortable:true,formatter:formatLevel},
			          {field:'seq',title:'显示顺序',width:100,sortable:true},
			          {field:'url',title:'链接页面',width:450,sortable:true},
			          {field:'parentName',title:'父级菜单',align:'center',width:150,sortable:true},
			          {field:'status',title:'状态',sortable:true,width:150,align:'center',formatter:formatStratus},
			          {field:'lastUpdatedDate',title:'更新时间',width:150,sortable:true,formatter:formatTime},
			          {field:'_operate',title:'操作',width:120,fit:true,align:'center',formatter:formatOper},
			      ]],
			 onSortColumn: function (sort, order) {
				 setPager(pager,result.total);
             }
		});
		
		pager = $('#menuGrid').datagrid().datagrid('getPager');	// get the pager of datagrid
		setPager(pager,result.total);
		
		//新增或更新菜单
		$('.dealicon').on('click',edit);
		
		//禁用或者启用菜单
		$('.playicon,.disableicon').on('click',changeStatusMenu);
		
		//删除菜单
		$('.delicon').on('click',deleteMenu);
	});
}


function setPager(pager,total){
	pager.pagination({
		total:total,
		pageNumber:currentPage,
	    pageSize:defaultPageSize,
	    layout:['first','prev','links','next','last'],
	    onSelectPage:function(cpage, psize){
	    	currentPage=cpage;
	    	pageSize=psize;
	    	loadGrid();
		}
	});
}

var formatId = function(val, row,index){
	return (index+1)+(currentPage-1)*pageSize;
}

var formatLevel = function(val){
	if(val==1)
	{
		return '一级';
	}
	return '二级';
}

var formatStratus = function(val){
	if(val=='Y'){
		return '启用';
	}
	return '禁用';
}

var formatTime = function(val){
	if (val != null) {
		var date = new Date(val);
		return date.getFullYear() + '-' + (date.getMonth() + 1) + '-'+ date.getDate()+' '+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds();
	}
}

var formatOper = function(val,row,index){
	var oper = '';
	if(row.status=='N'){
		oper += '<a href="#;" class="playicon tips tipso_style funcbtn update_menu_status" row-id="'+row.id+'" data-tipso="启用"></a>';
	}else{
		oper += '<a href="#;" class="disableicon tips tipso_style funcbtn update_menu_status" row-id="'+row.id+'" data-tipso="禁用"></a>';
	}
	oper += '<a href="#" class="dealicon tips tipso_style ml10 funcbtn update_menu" row-id="'+row.id+'" data-tipso="编辑"></a> <a href="#;" class="delicon tips tipso_style ml10 funcbtn delete_menu" row-id="'+row.id+'" data-tipso="删除"></a>';
	return oper;
}

function search(){
	var keywords = $('#keywords').val();
	if(keywords!='')
	{
		currentPage = 1;
		pageSize = defaultPageSize;
		params.name = keywords;
		loadGrid();
	}
}

function emptySearch(){
	$('#keywords').val('');
	params = {};
	loadGrid();
}

function changeStatusMenu(){
	var id = $(this).attr('row-id');
	var status='';
	var clickStatus = $(this).hasClass("playicon");
	if(clickStatus)//启用
	{
		status = 'Y';
	}else{//禁用
		status = 'N';
	}
	
	$.ajax({
		url:webUrl+'sysmenu/updateStatusSysMenu.do',
		type:'post',
		data:{id:id,status:status}
	}).done(function(data){
		loadNav();
		loadGrid();
	});
}

function add(){
	var dialog_info = {};
	dialog_info.title = '新增菜单';
	dialog_info.yesbtn = '保存';
	saveOrupdateMenu(dialog_info);
}

function edit(){
	var id = $(this).attr('row-id');

	var dialog_info = {};
	dialog_info.title = '更新菜单';
	dialog_info.yesbtn = '修改';
	dialog_info.id = id;
	saveOrupdateMenu(dialog_info);
	getMenuInfoById(id);
}

function saveOrupdateMenu(dialog_info){
	findAllParentMenu();
	alliconMenu();
	new Dialog({
			target:'#dialogbox',
			width:600,
		/*	height:500,*/
			showYesBtn:true,
			showNoBtn:true,
			title: dialog_info.title,
			yesBtnText:dialog_info.yesbtn,
			noBtnText:'取消',
			yesFn:function(){saveOrupdateMenuData(this,dialog_info.id)},
			noFn:function(){emptyBox()}}).show();
}

function saveOrupdateMenuData(obj,id){
	var params = {};
	var flag = true;
	var type = $('#menutype').val();
	if(type==''){
		$('#menutype').css({'border-color':'red'});
		flag = false;
		obj.boolConfirm = false;
	}else if(type=='sub'){
		var parentId = $('#parentmenu').val();
		if(parentId == '')
		{
			$('#parentmenu').css({'border-color':'red'});
			flag = false;
			obj.boolConfirm = false;
		}else{
			$('#parentmenu').css({'border-color':''});
		}
		params.parentId = parentId;
		params.level = 2;
		$('#menutype').css({'border-color':''});
	}else if(type=='top'){
		params.level = 1;
		$('#menutype').css({'border-color':''});
	}
	
	var hasicon = $('#iconmenu .subicon').hasClass('active');
	if(!hasicon)
	{
		 $('#iconmenu').css({'border':'1px solid red'});
		 flag = false;
		 obj.boolConfirm = false;
	}else{
		$('#iconmenu').css({'border':''});
	}
	
	var name = $('#menuname').val();
	if(name=='')
	{
		$('#menuname').css({'border-color':'red'});
		flag = false;
		obj.boolConfirm = false;
	}else{
		if(hasMenuName(name,id)){
			$('#menuname').css({'border-color':'red'});
			$('#existerrormsg').text('已存在');
			flag = false;
			obj.boolConfirm = false;
		}else{
			$('#menuname').css({'border-color':''});
			$('#existerrormsg').text('');
		}
	}

	if($('#menuseq').val()<1)
	{
		$('#menuseq').css({'border-color':'red'});
		flag = false;
		obj.boolConfirm = false;
	}else{
		$('#menuseq').css({'border-color':''});
	}

	if(flag)
	{
		obj.boolConfirm = true;
		params.id = id;
		params.name = name;
		params.url = $('#menuurl').val();
		params.seq = $('#menuseq').val();
		params.note = $('#menunote').val();
		params.icon = $('#iconmenu .active').attr('icon');

		var url = webUrl+'sysmenu/updateSysMenu.do';
		if(id==undefined)
		{
			url = webUrl+'sysmenu/saveSysMenu.do';
		}
		
		$.ajax({
			url:url,
			type:'post',
			data:params
		}).done(function(data){
			loadNav();
			loadGrid();
			emptyBox();
		});
	}
}

function getMenuInfoById(id){
	$.ajax({
		url:webUrl+'sysmenu/getSysMenuById.do',
		data:{id:id}
	}).done(function(data){
		var result = data.bo;
		if(result.level==1)
		{
			$('#menutype').val('top');
		}else{
			$('#menutype').val('sub');
			$('#parentmenu').val(result.parentId);
		}
		selecttype($('#menutype'));
		$('#menuname').val(result.name);
		$('#menuurl').val(result.url);
		$('#menuseq').val(result.seq);
		$('#menunote').val(result.note);
		$('#iconmenu .subicon[icon="'+result.icon+'"]').addClass('active');
	});
}

function emptyBox(){
	$('input,#menutype').css({'border-color':''});
	$('#iconmenu').css({'border':''});
	$('#menutype,#menuname,#menuurl,#menunote,#menuseq').val('');
}

function selecttype(obj){
	$('#iconmenu .subicon').on('click',function(){
		$('#iconmenu .subicon').removeClass('active');
		$(this).addClass('active');
	});
	
	if($(obj).val()=='sub')
	{
		$('.disabledmenu').removeAttr("disabled");
	}else{
		$('.disabledmenu').val('');
		$('.disabledmenu').attr("disabled","disabled");
	}
}

function findAllParentMenu(){
	var params = {};
	params.level = 1;
	$.ajax({
		url: webUrl+'sysmenu/findSysMenu.notPermSc',
		data:params
	}).done(function(data){
		var result = data.bo;
		$('#parentmenu').empty().append('<option value=""></option>');
		for(var i=0;i<result.length;i++)
		{
			$('#parentmenu').append('<option value="'+result[i].id+'">'+result[i].name+'</option>');
		}
	});
}

function alliconMenu(){
	$('#iconmenu').empty().append('<b></b>');
	for(var i=1;i<20;i++)
	{
		$('#iconmenu').append('<b icon="subicon icon'+i+'" class="subicon icon'+i+'"></b>');
	}
	
}

function deleteMenu(){
	var id = $(this).attr('row-id');
	var tips = '';
	$.ajax({
		url:webUrl+'sysmenu/hasSubSysMenu.do',
		data:{id:id}
	}).done(function(data){
		if(data.bo)
		{
			tips = '存在子菜单，确认是否删除?';
		}else{
			tips = '确认是否删除?';
		}
		deleteTips(id,tips);
	});
}

function deleteTips(id,tips){
	$("#tipsInfo").html('<b class="sighicon"></b>'+tips);
	new Dialog({
		target:'#tipsbox',
		width:300,
		height:160,
		showYesBtn:true,
		showNoBtn:true,
		yesFn:function(){
			deleteMenuData(id);
		},
		noFn:function(){}
		}).show();
}

function deleteMenuData(id){
	$.ajax({
		url:webUrl+'sysmenu/deleteSysMenu.do',
		type:'post',
		data:{id:id}
	}).done(function(data){
		loadNav();
		loadGrid();
	});
}

function hasMenuName(name,id){
	var has = false;
	var params = {};
	params.name=name;
	params.id=id;
	$.ajax({
		url:webUrl+'sysmenu/hasMenuNameSysMenu.do',
		type:'post',
		async:false,
		data:params
	}).done(function(data){
		has = data.bo;
	});
	return has;
}

